package com.huibao.hulibao.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.example.zhouwei.library.CustomPopWindow;
import com.huibao.hulibao.R;
import com.huibao.hulibao.adapter.BabyPopLvAdapter;
import com.huibao.hulibao.adapter.HuLiViewPgaerAdapter;
import com.huibao.hulibao.adapter.HuliDetailBindMomGvAdapter;
import com.huibao.hulibao.adapter.HuliDetailGvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.HuLiBindMomEntity;
import com.huibao.hulibao.entity.HuLiDetailDataEntity;
import com.huibao.hulibao.entity.HuLiEntity;
import com.huibao.hulibao.entity.HuLiRoomEntity;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.T;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lizhaoyong on 2018/5/9.
 */
public class HuliDetailActivity extends BaseActivity {


    @BindView(R.id.tv_hulifangjiang)
    TextView tv_hulifangjiang;
    @BindView(R.id.tv_bindmom)
    TextView tv_bindmom;
    @BindView(R.id.vp_huli_detail)
    ViewPager vp_huli_detail;
    @BindView(R.id.iv_title)
    ImageView iv_title;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.ll_main)
    LinearLayout ll_main;

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_back)
    TextView tv_back;

    // 数据请求成功切换页面不再请求数据
    private boolean is_room_data_ok = false;
    private boolean is_bind_mom_data_ok = false;


    // 网络请求加载对话框
    private Dialog myDialog;

    private HuLiEntity.HuLiData hd;
    private HuLiRoomEntity hre;
    private HuLiBindMomEntity hbme;
    private String session;
    private String str_type;

    private ArrayList<View> al_views;
    private GridView gv1;
    private GridView gv2;
    // 测试数据
    private ArrayList<String> al_tests;
    private ArrayList<String> al_tests_two;
    private ArrayList<String> al_tests_pop_baby;

    private ListView lv_pop_baby;
    private String id;
    private String pic;


    @OnClick({R.id.iv_back, R.id.tv_back})
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_hulifangjiang)
    public void hulifangjian() {
        fristSelected();
        vp_huli_detail.setCurrentItem(0);
    }

    @OnClick(R.id.tv_bindmom)
    public void bindmom() {
        secondSelected();
        vp_huli_detail.setCurrentItem(1);
    }

    public void fristSelected() {
        tv_hulifangjiang.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_selected));
        tv_bindmom.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_no_selected));
    }

    public void secondSelected() {
        tv_hulifangjiang.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_no_selected));
        tv_bindmom.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_selected));
    }


    // 显示多个宝宝选择的popwindow
    public void showBabyPop(final ArrayList<HuLiDetailDataEntity.RooMInfo> al_babys, final String room_id, final String customer_id, final String room_name) {
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int heigh = wm.getDefaultDisplay().getHeight();

        final CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(HuliDetailActivity.this)
                .setView(R.layout.popwindow_baby)
                .setFocusable(true)
                .size(width, heigh)
                .setOutsideTouchable(true)
                // pop消失监听
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                })
                .create();

        lv_pop_baby = (ListView) popWindow.getPopupWindow().getContentView().findViewById(R.id.lv_pop_baby);
        lv_pop_baby.setAdapter(new BabyPopLvAdapter(al_babys, getApplicationContext()));
        TextView tv_close = (TextView) popWindow.getPopupWindow().getContentView().findViewById(R.id.tv_close);
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dissmiss();
            }
        });


        lv_pop_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HuLiDetailDataEntity.RooMInfo rm = al_babys.get(i);
                Intent intent = new Intent(HuliDetailActivity.this, StartHuliActivity.class);
                intent.putExtra("pid", rm.BabyId);
                intent.putExtra("session", session);
                intent.putExtra("nid", hd.i);
                intent.putExtra("roomid", room_id);
                intent.putExtra("customerid", customer_id);
                intent.putExtra("motherid", rm.MatherId);
                intent.putExtra("babyid", rm.BabyId);
                intent.putExtra("type", str_type);
                intent.putExtra("room_name", room_name);
                intent.putExtra("mom_name", rm.MatherName);
                intent.putExtra("pic", pic);
                intent.putExtra("baby_name", rm.BabyName);
                intent.putExtra("mom_data", hd);
                intent.putExtra("title", tv_title.getText().toString());
                startActivity(intent);


                popWindow.dissmiss();
            }
        });
        // 设置显示位置
        // popWindow.showAsDropDown(iv_title, 0, 0);
        popWindow.showAtLocation(ll_main, Gravity.CENTER, 0, 0);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huli_detail);
        ButterKnife.bind(this);
        hd = (HuLiEntity.HuLiData) getIntent().getSerializableExtra("mom_data");
        // 1.妈妈护理 2.宝宝护理
        str_type = getIntent().getStringExtra("type");
        // 显示图片
        pic = getIntent().getStringExtra("pic");
        if (pic != null && !pic.equals("")) {
            Glide.with(this).load(GlobalConstants.HOST + pic).into(iv_title);

        }

        if (str_type.equals("1")) {
            tv_bindmom.setText(getResources().getString(R.string.bindmom));
        } else if (str_type.equals("2")) {
            tv_bindmom.setText(getResources().getString(R.string.bindbaby));
        }
        session = getIntent().getStringExtra("session");
        // LogUtils.d("session = " + session);
        if (hd != null) {
            id = hd.i;
            tv_title.setText(hd.n);
            // 获取房间
            getServerDetailData(0);
        }
        initViews();

    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(HuliDetailActivity.this, getResources().getString(R.string.jiazaizhong));
    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    public void getServerDetailData(final int type) {
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
//        JSONObject object = new JSONObject();
//        try {
//            object.put("type", type);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        if (type == 0) {
            params.addBodyParameter("q", session + GlobalConstants.URL_HULI_ROOM + "-");
        } else if (type == 1) {
            params.addBodyParameter("q", session + GlobalConstants.URL_BIND_MOM + "-");
        }


        // LogUtils.d("params = " + params.toString());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);

                    if (type == 0) {
                        hre = GlobalConstants.gson.fromJson(jsonObject.toString(), HuLiRoomEntity.class);
                        is_room_data_ok = true;
                        if (hre != null && hre.State.equals(GlobalConstants.SUCCESS_CODE)) {
                            // 设置数据
                            gv1.setAdapter(new HuliDetailGvAdapter(getApplicationContext(), hre.Message));
                            gv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    // 获取房间详细数据,判断后进入开始护理页面
                                    getRoomDetailData(hre.Message.get(i).RoomId, hre.Message.get(i).CustomerId, hre.Message.get(i).RoomName);
                                }
                            });
                        }
                    } else if (type == 1) {
                        hbme = GlobalConstants.gson.fromJson(jsonObject.toString(), HuLiBindMomEntity.class);
                        is_bind_mom_data_ok = true;
                        if (hbme != null && hbme.State.equals(GlobalConstants.SUCCESS_CODE)) {
                            gv2.setAdapter(new HuliDetailBindMomGvAdapter(getApplicationContext(), hbme.Message, str_type));
                            // 护理多个宝宝的可能
                            gv2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    // 获取MOM详细数据,判断后进入开始护理页面
                                    getRoomDetailData(hbme.Message.get(i).roomid, hbme.Message.get(i).cid, hbme.Message.get(i).roomname);
                                }
                            });
                        }
                    }


                    // LogUtils.d("result = " + jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }


    // 获取房间详细数据用于传递到下个页面
    public void getRoomDetailData(final String room_id, final String customer_id, final String room_name) {
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();

        JSONObject object = new JSONObject();
        try {
            object.put("roomid", room_id);
            object.put("customerid", customer_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", session + GlobalConstants.URL_ROOM_DETAIL + object.toString());
        // LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    // LogUtils.d("result = " + jsonObject.toString());
                    HuLiDetailDataEntity hdde = GlobalConstants.gson.fromJson(jsonObject.toString(), HuLiDetailDataEntity.class);

                    if (hdde != null && hdde.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        // LogUtils.d("str_type = " + str_type);
                        // 妈妈护理
                        if (str_type.equals("1")) {
                            for (int i = 0; i < hdde.Message.size(); i++) {
                                if (hdde.Message.get(i).IsMom.equals("1")) {
                                    Intent intent = new Intent(HuliDetailActivity.this, StartHuliActivity.class);
                                    intent.putExtra("pid", hdde.Message.get(i).MatherId);
                                    intent.putExtra("session", session);
                                    intent.putExtra("nid", hd.i);
                                    intent.putExtra("roomid", room_id);
                                    intent.putExtra("customerid", customer_id);
                                    intent.putExtra("motherid", hdde.Message.get(i).MatherId);
                                    intent.putExtra("babyid", hdde.Message.get(i).BabyId);
                                    intent.putExtra("type", str_type);
                                    intent.putExtra("room_name", room_name);
                                    intent.putExtra("pic", pic);
                                    intent.putExtra("mom_name", hdde.Message.get(i).MatherName);
                                    intent.putExtra("baby_name", hdde.Message.get(i).BabyName);
                                    intent.putExtra("mom_data", hd);
                                    intent.putExtra("title", tv_title.getText().toString());
                                    startActivity(intent);
                                    break;
                                }
                            }
                            // 宝宝护理
                        } else if (str_type.equals("2")) {

                            ArrayList<HuLiDetailDataEntity.RooMInfo> al = new ArrayList<HuLiDetailDataEntity.RooMInfo>();
                            for (int i = 0; i < hdde.Message.size(); i++) {
                                if (hdde.Message.get(i).IsMom.equals("0")) {
                                    al.add(hdde.Message.get(i));
                                }
                            }

                            // 如果有多重情况
                            if (al.size() > 1) {
                                // 弹出POP让用户选择后关闭
                                showBabyPop(al, room_id, customer_id, room_name);
                                // 如果是单一类型
                            } else if (al.size() == 1) {
                                Intent intent = new Intent(HuliDetailActivity.this, StartHuliActivity.class);
                                intent.putExtra("pid", al.get(0).BabyId);
                                intent.putExtra("session", session);
                                intent.putExtra("nid", hd.i);
                                intent.putExtra("pic", pic);
                                intent.putExtra("roomid", room_id);
                                intent.putExtra("customerid", customer_id);
                                intent.putExtra("motherid", al.get(0).MatherId);
                                intent.putExtra("babyid", al.get(0).BabyId);
                                intent.putExtra("type", str_type);
                                intent.putExtra("room_name", room_name);
                                intent.putExtra("mom_name", al.get(0).MatherName);
                                intent.putExtra("baby_name", al.get(0).BabyName);
                                intent.putExtra("mom_data", hd);
                                intent.putExtra("title", tv_title.getText().toString());
                                startActivity(intent);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }


    private void initViews() {

        al_tests = new ArrayList<String>();
        al_tests_two = new ArrayList<String>();
        al_tests_pop_baby = new ArrayList<String>();

        al_tests_pop_baby.add("");
        al_tests_pop_baby.add("");


        View v1 = View.inflate(getApplicationContext(), R.layout.vp_huli_detail_one, null);
        View v2 = View.inflate(getApplicationContext(), R.layout.vp_huli_detail_two, null);
        gv1 = (GridView) v1.findViewById(R.id.gv_huli_detail_one);
        gv2 = (GridView) v2.findViewById(R.id.gv_huli_detail_two);


        // gv2.setAdapter(new HuliDetailGvAdapter(getApplicationContext(), al_tests_two));
        al_views = new ArrayList<View>();
        al_views.add(v1);
        al_views.add(v2);
        vp_huli_detail.setAdapter(new HuLiViewPgaerAdapter(al_views));

        vp_huli_detail.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    fristSelected();
                    if (is_room_data_ok == false) {
                        getServerDetailData(position);
                    }

                } else if (position == 1) {
                    if (is_bind_mom_data_ok == false) {
                        getServerDetailData(position);
                    }
                    secondSelected();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }
}
